package com.example.administrator.myapplication;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/17 0017.
 * 将正在运行的进程跟进程名称用ListView打印到布局中
 */
public class TestActivity extends Activity {
    private ListView mListView;
    private ActivityManager mActMgr;
    private PackageManager  mPackMgr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView = (ListView) findViewById(R.id.listView1);
        AppListAdapter adapter = new AppListAdapter(this,getProgram());
        mListView.setAdapter(adapter);

    }
    //得到正在运行的进程
    private List<Program> getProgram(){
        //创建进程的容器
        List<Program> list = new ArrayList<>();
        //获得系统中的所有进程
        //进程管理器
        mActMgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        //包管理器
        mPackMgr = getPackageManager();
        //得到所有运行的进程
        List<ActivityManager.RunningAppProcessInfo> runList = mActMgr.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo proc: runList) {
            try {
                ApplicationInfo appInfo = mPackMgr.getApplicationInfo(proc.processName, 0);
                //得到名字
                String name = appInfo.loadLabel(mPackMgr).toString();
                //得到Icon
                Drawable icon = appInfo.loadIcon(mPackMgr);

                System.out.println("应用程序的名字："+name);
                //将得到的进程存入List
                list.add(new Program(icon,name));

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
